package au.chao.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import au.chao.setting.ServerConfig;
import au.chao.socket.SocketException;

public class SocketUtil {
	/**
	 * Log4J Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SocketUtil.class);

	public static void closeSocket(Socket socket) {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				logger.error("Close socket failed", e);
			}
		}
	}

	public static void closeSocket(ServerSocket serverSocket) {
		if (serverSocket != null) {
			try {
				serverSocket.close();
			} catch (IOException e) {
				logger.error("Close server socket failed", e);
			}
		}
	}

	public SocketUtil() {
		// TODO Auto-generated constructor stub
	}

	public static void closeIOStream(ObjectInputStream inStream) {
		if (inStream != null) {
			try {
				inStream.close();
			} catch (IOException e) {
				logger.error("Close server socket failed", e);
			}
		}
	}

	public static void closeIOStream(ObjectOutputStream outStream) {
		if (outStream != null) {
			try {
				outStream.close();
			} catch (IOException e) {
				logger.error("Close server socket failed", e);
			}
		}
	}

	public static void isMessageServerRunning(final InetAddress remote)
			throws SocketException {
		try {
			new Socket(remote, ServerConfig.DEFAULT_SERVER_PORT_NUM);
		} catch (IOException ex) {
			throw new SocketException("Can not connect to message server "
					+ remote.getHostAddress(), ex);
		}
	}
}
